import React from 'react';
import { makeStyles, withStyles } from '@material-ui/core/styles';
import { Typography, Grid, Button, TextField } from '@material-ui/core';
import validate from 'validate.js';
import { LearnMoreLink } from 'components/atoms';
import { setProfile } from 'redux/actions/AuthActions'
import { useSelector, useDispatch } from 'react-redux'
import ReactHtmlParser from 'react-html-parser';
import { useHistory, useLocation } from "react-router-dom";
import { callPostNewsApi} from 'utils/networking';

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
  },
}));

const schema = {
  email: {
    presence: { allowEmpty: false, message: 'is required' },
    //email: true,
    length: {
      maximum: 255,
    },
  },
  password: {
    presence: { allowEmpty: false, message: 'is required' },
    length: {
      minimum: 6,
    },
  },
};

const RedTextTypography = withStyles({
  root: {
    color: "#FF0000",
    marginBottom: '20px'
  }
})(Typography);

const Form = (props) => {

  let { type, id } = props;

  const classes = useStyles();
  const preAuthPath = useSelector((state) => state.auth.preAuthPath);
  const [callbackError, setCallbackError] = React.useState('');

  const [formState, setFormState] = React.useState({
    isValid: false,
    values: {},
    touched: {},
    errors: {},
  });

  React.useEffect(() => {
    const errors = validate(formState.values, schema);
    setFormState(formState => ({
      ...formState,
      isValid: errors ? false : true,
      errors: errors || {},
    }));
  }, [formState.values]);

  const handleChange = event => {
    event.persist();

    setFormState(formState => ({
      ...formState,
      values: {
        ...formState.values,
        [event.target.name]:
          event.target.type === 'checkbox'
            ? event.target.checked
            : event.target.value,
      },
      touched: {
        ...formState.touched,
        [event.target.name]: true,
      },
    }));
  };

  const dispatch = useDispatch()
  let history = useHistory();

  const handleSubmit = event => {
    event.preventDefault();

    if (formState.isValid) {
      const param = {
        email: formState.values.email,
        password: formState.values.password
      }
      callPostNewsApi('user/login', param, dispatch, (data) => {
        dispatch(setProfile(data));
        localStorage.setItem("token", data.token);
        
        if (!data.phone) {
          history.replace('/verify-phone');
          return;
        }
        if (type && id) {
          if (type === 'playlist') {
            window.location.replace(`${process.env.REACT_APP_SERVER_URL}/player/playlist/${id}/${data.token}`);
            return;
          }
          else if (type === 'album') {
            window.location.replace(`${process.env.REACT_APP_SERVER_URL}/player/album/${id}/${data.token}`);
            return;
          }
          else if (type === 'song') {
            window.location.replace(`${process.env.REACT_APP_SERVER_URL}/player/play/${id}/${data.token}`);
            return;
          }
          else if (type === 'user') {
            window.location.replace(`${process.env.REACT_APP_SERVER_URL}/player/user/${id}/${data.token}`);
            return;
          }
          else if (type === 'episode') {
            window.location.replace(`${process.env.REACT_APP_SERVER_URL}/player/episode/${id}/${data.token}`);
            return;
          }
          else if (type === 'season') {
            window.location.replace(`${process.env.REACT_APP_SERVER_URL}/player/season/${id}/${data.token}`);
            return;
          }
        }

        if (type === 'playlist') {
          window.location.replace(`${process.env.REACT_APP_SERVER_URL}/playlist/index/${data.token}`);
          return;
        }

        if (preAuthPath) {
          history.replace(preAuthPath)
        }
        else {
          history.replace("")
        }
      }, (err) => {
        setCallbackError(err)
      })
    }

    setFormState(formState => ({
      ...formState,
      touched: {
        ...formState.touched,
        ...formState.errors,
      },
    }));
  };

  const hasError = field =>
    formState.touched[field] && formState.errors[field] ? true : false;

  return (
    <div className={classes.root}>
      {(
        <Grid item xs={12}>
          <RedTextTypography
            align="center"
            className={classes.errorLabel}
          >
            {ReactHtmlParser(callbackError)}
          </RedTextTypography>
        </Grid>
      )}
      <form name="password-reset-form" method="post" onSubmit={handleSubmit}>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <TextField
              placeholder="E-mail/Username"
              label="E-mail/Username *"
              variant="outlined"
              size="medium"
              name="email"
              fullWidth
              helperText={
                hasError('email') ? formState.errors.email[0] : null
              }
              error={hasError('email')}
              onChange={handleChange}
              type="text"
              value={formState.values.email || ''}
            />
          </Grid>
          <Grid item xs={12}>
            <TextField
              placeholder="Password"
              label="Password *"
              variant="outlined"
              size="medium"
              name="password"
              fullWidth
              helperText={
                hasError('password') ? formState.errors.password[0] : null
              }
              error={hasError('password')}
              onChange={handleChange}
              type="password"
              value={formState.values.password || ''}
            />
          </Grid>
          <Grid item xs={12}>
            <i>
              <Typography variant="subtitle2">
                Fields that are marked with * sign are required.
              </Typography>
            </i>
          </Grid>
          <Grid item xs={12}>
            <Button
              size="large"
              variant="contained"
              type="submit"
              color="primary"
              fullWidth
            >
              Submit
            </Button>
          </Grid>
          <Grid item xs={12}>
            <Typography
              variant="subtitle1"
              color="textSecondary"
              align="center"
            >
              Forgot your password?{' '}
              <LearnMoreLink
                title="Reset password"
                href="/password-reset-cover"
              />
            </Typography>
          </Grid>
        </Grid>
      </form>
    </div>
  );
};

export default Form;
